package com.yicong.ants.ui.me;

import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import androidx.databinding.DataBindingUtil;

import com.blankj.utilcode.util.ToastUtils;
import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.core.ImageLoader;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.model.event.CommonEvent;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.cchao.simplelib.util.CallBacks;
import com.cchao.simplelib.util.StringHelper;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.account.CheckAuth;
import com.yicong.ants.bean.account.UserBean;
import com.yicong.ants.bean.common.UploadImageBean;
import com.yicong.ants.databinding.OrderPayAuthBinding;
import com.yicong.ants.databinding.UserInfoActivityBinding;
import com.yicong.ants.manager.AppHelper;
import com.yicong.ants.manager.BusinessHelper;
import com.yicong.ants.manager.ImageHelper;
import com.yicong.ants.manager.PayManager;
import com.yicong.ants.manager.RpHelper;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.ad.AdManager;
import com.yicong.ants.manager.config.ZzConfigs;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.ui.me.account.IncomeEditActivity;
import com.yicong.ants.ui.me.address.AddressListActivity;
import com.zx.sdk.util.ConfigHelper;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 个人信息页
 *
 * @author cchao
 * @version 2019-06-14.
 */
public class UserInfoActivity extends BaseTitleBarActivity<UserInfoActivityBinding> implements View.OnClickListener {
    UserBean mUserBean;
    CheckAuth mCheckAuthBean;
    boolean mNeedAuthAgain;

    @Override
    protected int getLayout() {
        return R.layout.user_info_activity;
    }

    @Override
    protected void initEventAndData() {
        mNeedAuthAgain = getIntent().getBooleanExtra(Constants.Extra.To_Auth, false);
        setTitleText("个人信息");
        setTitleBarVisible(false);
        AppHelper.transStatus(getWindow());
        mDataBind.setClick(this);
        updateUserInfo();
        loadAd();
        if (mNeedAuthAgain && mUserBean.getIsAuth()) {
            checkAuth();
        }
        if (ConfigHelper.getShowInterstitialPages().contains("userInfo")) {
            AdManager.showInterstitial(this);
        }
    }

    private void loadAd() {
        AdManager.showBanner(this, mDataBind.adContainer);
    }

    void updateUserInfo() {
        mUserBean = UserManager.getUserBean();
        mDataBind.setBean(mUserBean);
        mDataBind.authStatus.setTextColor(UiHelper.getColor(mUserBean.getIsAuth() ? R.color.authentication : R.color.new_text_color_3));
        UiHelper.setVisibleElseGone(mDataBind.authWarning, mNeedAuthAgain);
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (event.getCode()) {
            case Constants.Event.Update_Me_Info:
                updateUserInfo();
                break;
            case Constants.Event.Auth_Suc:
                mNeedAuthAgain = false;
                updateUserInfo();
                finish();
                break;
            case Constants.Event.Pay_Result_Suc:
                UiHelper.showLongToast("支付成功！开始认证");
                startAuthType();
                break;
            case Constants.Event.Pay_Result_Fail:
                UiHelper.showConfirmDialog(mContext, "支付失败", null);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        showProgress();
        UserManager.refreshDashboard(str -> {
            hideProgress();
            mDataBind.setBean(UserManager.getUserBean());
        });
        UserManager.havePayPwd(this, intValue -> {
            mDataBind.havePayPwd.setText(intValue == 0 ? "" : "已设置");
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AdManager.destroyBanner(this);
    }

    /**
     * 根据类型跳转认证
     */
    private void startAuthType() {
        switch (mCheckAuthBean.getAuth_type()) {
            case 0:
                break;
            case 1:
                ZzConfigs.toWebActivityByUrl(mContext, "id_card_check");
                break;
            case 2:
                RpHelper.startVerify(thisActivity);
                break;
        }
    }

    @Override
    protected void onLoadData() {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }

        List<String> pathList = data.getStringArrayListExtra("result");
        if (CollectionHelper.isNotEmpty(pathList)) {
            uploadImage(pathList.get(0));
        }
    }

    /**
     * 上传图片
     * 通过 setTag 将网络请求结果的bean放入view，
     */
    public void uploadImage(String localUri) {
        UploadImageBean bean = new UploadImageBean();
        bean.setLocalUri(localUri);

        ImageHelper.uploadAvatar(mDisposable, bean, respBean -> {
            if (respBean.isCodeFail()) {
                showError();
                return;
            }
            ImageLoader.loadImage(mDataBind.avatar, localUri, R.drawable.place_holder);
            mUserBean.setAvatar(respBean.getData());
            UserManager.updateUserBean(mUserBean);
        }, throwable -> {
            showError();
            Logs.logException(throwable);
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                onBackPressed();
                break;
            case R.id.nickname_field:
                UiHelper.showEditDialog(mContext, "修改昵称", mUserBean.getNickname(), str -> {
                    // 提交请求
                    Map<String, String> map = new HashMap<>();
                    map.put("nickname", str);
                    showProgress();
                    addSubscribe(RetrofitHelper.getApis().updateNickName(map)
                            .compose(RxHelper.toMain())
                            .subscribe(respBean -> {
                                hideProgress();
                                if (respBean.isCodeFail()) {
                                    showToast(respBean.getMsg());
                                    return;
                                }
                                mUserBean.setNickname(str);
                                UserManager.updateUserBean(mUserBean);
                            }, RxHelper.getHideProgressConsumer(UserInfoActivity.this)));
                });
                break;
            case R.id.wx_field:
                UiHelper.showEditDialog(mContext, "修改微信号", mUserBean.getWx_account(), str -> {
                    if (StringHelper.isEmpty(str)) {
                        return;
                    }
                    // 提交请求
                    Map<String, String> map = new HashMap<>();
                    map.put("wx_account", str);
                    showProgress();
                    addSubscribe(RetrofitHelper.getApis().updateWxAccount(map)
                            .compose(RxHelper.toMain())
                            .subscribe(respBean -> {
                                hideProgress();
                                if (respBean.isCodeFail()) {
                                    showToast(respBean.getMsg());
                                    return;
                                }
                                mUserBean.setWx_account(str);
                                updateUserInfo();
                            }, RxHelper.getHideProgressConsumer(UserInfoActivity.this)));
                });
                break;
            case R.id.x5webview:
                UiHelper.showItemsDialog(mContext, "修改性别", new String[]{"女", "男"}, (dialogInterface, i) -> {
                    // 提交请求
                    Map<String, String> map = new HashMap<>();
                    map.put("gender", String.valueOf(i));
                    showProgress();
                    addSubscribe(RetrofitHelper.getApis().updateGender(map)
                            .compose(RxHelper.toMain())
                            .subscribe(respBean -> {
                                hideProgress();
                                if (respBean.isCodeFail()) {
                                    showToast(respBean.getMsg());
                                    return;
                                }
                                mUserBean.setGender(String.valueOf(i));
                                mUserBean.setGender_text(i == 0 ? "女" : "男");
                                UserManager.updateUserBean(mUserBean);
                            }, RxHelper.getHideProgressConsumer(UserInfoActivity.this)));
                });
                break;
            case R.id.address_field:
                Router.turnTo(mContext, AddressListActivity.class).start();
                break;
            case R.id.start_rule:
                ZzConfigs.toWebActivityByUrlNotLogin(mContext, "ant_rule_star");
                break;
            case R.id.income_field:
                Router.turnTo(mContext, IncomeEditActivity.class).start();
                break;
            case R.id.avatar_field:
                ImageHelper.takeImage(thisActivity, localMediaList -> uploadImage(localMediaList.get(0).getCompressPath()));
                break;
            case R.id.pay_pwd_field:
                // 支付密码设置
                Router.turnTo(mContext, PayPwdSettingActivity.class).start();
                break;
            case R.id.auth_field:
                if (!mNeedAuthAgain && mUserBean.getIsAuth()) {
                    showToast("你已经认证过了");
                    return;
                }
                checkAuth();
                break;
            case R.id.tourist_identity_field:
                UserManager.getScenicQrCode(str -> BusinessHelper.showTouristQr(getWindow(), mContext, str));
            case R.id.voucher_code:
                break;
        }
    }

    /**
     * 是否需要认证
     */
    private void checkAuth() {
        showProgress();
        addSubscribe(RetrofitHelper.getApis().checkRp2(Collections.emptyMap())
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    if (respBean.isCodeFail()) {
                        ToastUtils.showShort(respBean.getMsg());
                        return;
                    }
                    mCheckAuthBean = respBean.getData();
                    // 无需
                    if (mCheckAuthBean.getAuth_type() == 0) {
                        return;
                    }
                    // 需要支付
                    if (mCheckAuthBean.getPay_price() <= 0) {
                        startAuthType();
                    } else {
                        UiHelper.showConfirmActionDialog(mContext, mCheckAuthBean.getPay_tip(), (dialog, which) -> {
                            //
                            showPayWindows();
                        });
                    }
                }, RxHelper.getHideProgressConsumer(this)));
    }

    public void showPayWindows() {
        OrderPayAuthBinding binding = DataBindingUtil.inflate(mLayoutInflater, R.layout.order_pay_auth, null, false);
        binding.payAuthContent.setText(mCheckAuthBean.getPay_tip());
        PopupWindow popupWindow = new PopupWindow(binding.getRoot(), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        // 外部点击事件
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(mDataBind.getRoot(), Gravity.BOTTOM, 0, 0);
        binding.setClick(v -> {
            switch (v.getId()) {
                case R.id.root:
                    popupWindow.dismiss();
                    break;
                case R.id.apply:
                    UiHelper.showToast("正在发起付款");

                    PayManager.CUR_PAY_CATEGORY = "rp_verify";
                    boolean isAli = binding.checkAliPay.isChecked();
                    Map<String, String> params = new HashMap<>();
                    params.put("type", isAli ? "alipay" : "wechat");
                    if (isAli) {
                        PayManager.payByAli(UserInfoActivity.this, params);
                    } else {
                        PayManager.payByWeChat(UserInfoActivity.this, params);
                    }
                    popupWindow.dismiss();
                    break;
                case R.id.back:
                    onBackPressed();
                    break;
                case R.id.rel_alipay:
                    binding.checkAliPay.setChecked(true);
                    binding.checkWechat.setChecked(false);
                    break;
                case R.id.rel_wechat:
                    binding.checkWechat.setChecked(true);
                    binding.checkAliPay.setChecked(false);
                    break;
            }
        });
    }
}
